package com.generator.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.generator.DTO.LoginDTO;
import com.generator.dao.SysUserDao;
import com.generator.entity.UserEntity;
import com.generator.service.SysUserService;
import com.generator.utils.JSONUtils;
import com.generator.utils.RedisUtils;
import com.generator.utils.Result;
import com.generator.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @Author Xing
 * @Date 2023/12/3 22:05
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, UserEntity> implements SysUserService {
    @Autowired
    private SysUserDao dao;
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public Result login(LoginDTO user) {
        if (user.getCode() == null) {
            user.setCode("1111");
        }
        System.out.println(user.getCode().toUpperCase());
        String code = "";
        try{
            code = (String) redisUtils.get("code:" + user.getKey());
        }catch (Exception e){
            return new Result().err(301,"验证码失效");
        }
        if (!code.equals(user.getCode().toUpperCase())){
            System.out.println(6156);
            return new Result().err(302,"验证码错误");
        }
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        UserEntity entity = dao.selectOne(queryWrapper);
        if (entity != null) {
            boolean equals = new BCryptPasswordEncoder().matches(user.getPassword(),entity.getPassword());
            if (equals){
                String replace = UUID.randomUUID().toString().replace("-", "");
                redisUtils.set("token:"+replace, JSONUtils.objToJson(entity),60*60*2,TimeUnit.MINUTES);
                return new Result().ok(replace);
            }
        }
        return new Result().err(403,"账号或密码错误");
    }

    @Override
    public UserEntity getByUsername(String username) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        UserEntity entity = dao.selectOne(queryWrapper);
        return entity;
    }

    @Override
    public void getArticle(HttpServletResponse response, String key) {
        if (key==null||key.equals("")){
            key="xing";
        }
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            String code = VerifyCodeUtils.outputVerifyImage(120, 40, outputStream,5);
            if (!StringUtils.hasText(code)){
                //为空处理
                System.out.println("注册模块：生成验证码错误");
            }
            redisUtils.set("code:"+key,code,5, TimeUnit.MINUTES);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (!ObjectUtils.isEmpty(outputStream)){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public Result register(LoginDTO user) {
        System.out.println(user);
        if (user.getCode() == null) {
            user.setCode("1111");
        }
        System.out.println(user.getCode().toUpperCase());
        String code = "";
        try{
            code = (String) redisUtils.get("code:" + user.getKey());
        }catch (Exception e){
            return new Result().err(301,"验证码失效");
        }
        if (!code.equals(user.getCode().toUpperCase())){
            System.out.println(6156);
            return new Result().err(302,"验证码错误");
        }
        UserEntity byUsername = getByUsername(user.getUsername());
        if (byUsername!=null) {
            return new Result().err(501,"该账号已被注册");
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(user.getUsername());
        userEntity.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        userEntity.setSign("无");
        dao.insert(userEntity);
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        UserEntity entity = dao.selectOne(queryWrapper);
        if (entity != null) {
            boolean equals = new BCryptPasswordEncoder().matches(user.getPassword(),entity.getPassword());
            if (equals){
                String replace = UUID.randomUUID().toString().replace("-", "");
                redisUtils.set("token:"+replace, JSONUtils.objToJson(entity),60*60*2,TimeUnit.HOURS);
                return new Result().ok(replace);
            }
        }
        return new Result().err(403,"账号或密码错误");
    }
}
